#!/usr/bin/python
# -*- coding: utf-8 -*-
"""docstrings
"""

import traceback
import sys

from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.ext import db

from net4.common import util
from posts import Post
from urls import URL

__all__ = ['VisitRecord', 'Post']

class VisitRecord(db.Model):
    """用户访问记录，用于调用google图标控件的数据"""
    
    BROWSER_NAMES = ('MSIE3', 'MSIE4', 'MSIE5', 'MSIE6', 'MSIE7', 'MSIE8',
                     'Firefox1', 'Firefox2', 'Firefox3',
                     'Chrome0', 'Chrome1',
                     'Safari1', 'Safari2', 'Safari3',
                     )
    OS_NAMES = ('Windows NT 6.0', 'Windows NT 5.2', 'Windows NT 5.1', 'Windows NT 5.0', 'Windows NT',
                'Linux i686',
                )
    
    uri = db.StringProperty()
    method = db.CategoryProperty()
    user_agent = db.StringProperty()
    accept = db.StringProperty()
    accept_language = db.StringProperty()
    accept_charset = db.StringProperty()
    referer = db.StringProperty()
    ip = db.StringProperty()
    ip_location = db.StringProperty()
    user = db.UserProperty()
    response_status = db.IntegerProperty() #记录请求状态
    exception = db.TextProperty()
    browser = db.CategoryProperty()
    os = db.CategoryProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    
    def _analysis_user_agent(self, user_agent):
        r = util.analysis_user_agent(user_agent)
        if r:
            self.os = r['os']
            if '/' in r['browser']:
                name, version = r['browser'].split('/')
            else:
                name, version = r['browser'].split(' ')
            self.browser = db.Category(name + version[0])
    
    def record(self, request, response, error=None):
        self.uri = request.get_full_path() # request.build_absolute_uri()
        self.method = db.Category(request.method)
        self.user_agent = request.META.get('HTTP_USER_AGENT', None)
        self._analysis_user_agent(self.user_agent)
        self.accept = request.META.get('HTTP_ACCEPT', None)
        self.accept_language = request.META.get('HTTP_ACCEPT_ENCODING', None)
        self.accept_charset = request.META.get('HTTP_ACCEPT_LANGUAGE', None)
        self.referer = request.META.get('HTTP_REFERER', None)
        self.ip = request.META['REMOTE_ADDR']
        self.hostname = request.META.get('REMOTE_HOST', None)
        self.user = users.get_current_user()
        self.response_status = response.status_code
        if error is not None:
            self.exception = ''.join(traceback.format_exception(*sys.exc_info()))
        self.put()